﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MicService.GrpcServer.Services;
using ProtoBuf.Grpc.Server;
using ProtobufNet.ProtoServices;
using System.Threading.Tasks;

namespace MicService.GrpcServer
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            // services.AddGrpc();
            services.AddCodeFirstGrpc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>();
                endpoints.MapGrpcService<HealthCheckService>();
                endpoints.MapGrpcService<protobufService>();
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });

            Task task = app.UseGRPCConsul(
            //new ConsulConfigModel() { IP = "127.0.0.1", Port = 8500 },
            new ConsulConfigModel() { IP = "192.168.106.128", Port = 8500 },
            new HealConfigMol 
            {
                IP = this.Configuration["ip"],
                Port = int.Parse(this.Configuration["Port"]),
                CheckPort = int.Parse(this.Configuration["Port"]),
                GroupName = "GRpcGroupName",
                Tag = new string[] { "Tag" }
            });
        }
    }
}